package info.empathymobile.batterymonitorapp;

import info.empathymobile.monitor.business.DatabaseHelper;
import info.empathymobile.monitor.business.OrmLiteBase;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.IBinder;

import com.j256.ormlite.android.apptools.OrmLiteBaseService;

public class ServerSyncService extends OrmLiteBaseService<DatabaseHelper> implements OrmLiteBase<DatabaseHelper> {

	private BatteryReceiverToServerSync batteryReceiverToServerSync = new BatteryReceiverToServerSync();
	private ConnectivityReceiverToServerSync connectivityReceiverToServerSync = new ConnectivityReceiverToServerSync();
	private boolean receiversToServerSyncRegistered = false;

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		registerServerSyncReceivers();
		return START_STICKY;
	}

	private void registerServerSyncReceivers() {
		IntentFilter batteryReceiverIntentFilter = new IntentFilter();
		batteryReceiverIntentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
		this.registerReceiver(batteryReceiverToServerSync, batteryReceiverIntentFilter);
		
		this.registerReceiver(connectivityReceiverToServerSync, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
		
		receiversToServerSyncRegistered = true;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		if(receiversToServerSyncRegistered){
			this.unregisterReceiver(batteryReceiverToServerSync);
			this.unregisterReceiver(connectivityReceiverToServerSync);
		}
	}
}
